#!/usr/bin/env node

/**
 * 日志功能测试脚本
 */

import { DatabaseMCPServer } from './core/DatabaseMCPServer.js';
import { LoggingService } from './logging/LoggingService.js';

async function testLoggingFeatures() {
  console.log('🚀 开始测试日志记录功能...\n');

  let server: DatabaseMCPServer | null = null;
  
  try {
    // 1. 初始化服务器
    console.log('1️⃣ 初始化 MCP 服务器...');
    server = new DatabaseMCPServer();
    await server.initialize();
    console.log('✅ MCP 服务器启动成功\n');

    // 获取日志服务实例
    const loggingService = (server as any).loggingService as LoggingService;
    if (!loggingService) {
      throw new Error('日志服务未初始化');
    }

    // 2. 测试手动日志记录
    console.log('2️⃣ 测试手动日志记录...');
    
    const measure1 = loggingService.createMeasure('search_antd_components', { query: 'Button', limit: 10 });
    await new Promise(resolve => setTimeout(resolve, 150)); // 模拟执行时间
    await measure1.success({ results: ['Button', 'IconButton'], count: 2 });
    console.log('✅ 成功记录工具调用: search_antd_components\n');

    const measure2 = loggingService.createMeasure('generate_antd_code', { 
      component: 'Button', 
      props: { type: 'primary', size: 'large' } 
    });
    await new Promise(resolve => setTimeout(resolve, 200));
    await measure2.success({ 
      code: '<Button type="primary" size="large">Click me</Button>',
      imports: ['Button'] 
    });
    console.log('✅ 成功记录工具调用: generate_antd_code\n');

    // 3. 测试错误记录
    console.log('3️⃣ 测试错误记录...');
    const measure3 = loggingService.createMeasure('get_antd_documentation', { component: 'NonExistentComponent' });
    await new Promise(resolve => setTimeout(resolve, 50));
    await measure3.error('Component not found');
    console.log('✅ 成功记录错误日志\n');

    // 4. 等待日志刷新
    console.log('4️⃣ 等待日志批量写入...');
    await new Promise(resolve => setTimeout(resolve, 5000)); // 等待更长时间确保批量写入
    console.log('✅ 日志批量写入完成\n');

    // 5. 测试获取最近日志
    console.log('5️⃣ 测试获取最近日志...');
    const recentLogs = await loggingService.getRecentLogs(10);
    console.log('📊 获取到 ' + recentLogs.length + ' 条最近日志:');
    recentLogs.forEach((log, index) => {
      console.log('  ' + (index + 1) + '. ' + log.tool_name + ' - ' + log.status + ' (' + log.execution_time_ms + 'ms)');
    });
    console.log();

    // 6. 测试使用分析
    console.log('6️⃣ 测试使用分析功能...');
    const analytics = await loggingService.getUsageAnalytics();
    console.log('📈 使用分析结果:');
    console.log('  - 总调用次数: ' + analytics.totalCalls);
    console.log('  - 成功率: ' + (analytics.successRate * 100).toFixed(1) + '%');
    console.log('  - 平均执行时间: ' + analytics.avgExecutionTime.toFixed(2) + 'ms');
    console.log('  - 热门工具: ' + analytics.topTools.map(t => t.toolName + '(' + t.calls + ')').join(', '));
    console.log();

    // 7. 测试每日报告
    console.log('7️⃣ 测试每日报告功能...');
    const today = new Date().toISOString().split('T')[0];
    const dailyReport = await loggingService.getDailyReport(today);
    console.log('📅 ' + today + ' 日报:');
    console.log('  - 总调用: ' + dailyReport.summary.totalCalls);
    console.log('  - 成功率: ' + (dailyReport.summary.successRate * 100).toFixed(1) + '%');
    console.log('  - 平均响应时间: ' + dailyReport.summary.avgExecutionTime.toFixed(2) + 'ms');
    console.log('  - 热门工具: ' + dailyReport.toolBreakdown.map(t => t.toolName + '(' + t.calls + ')').join(', '));
    console.log();

    // 8. 测试工具特定日志
    console.log('8️⃣ 测试工具特定日志...');
    const buttonLogs = await loggingService.getRecentLogs(5, 'search_antd_components');
    console.log('🔍 search_antd_components 工具最近 ' + buttonLogs.length + ' 条日志:');
    buttonLogs.forEach((log, index) => {
      console.log('  ' + (index + 1) + '. ' + log.status + ' - ' + log.execution_time_ms + 'ms');
    });
    console.log();

    console.log('🎉 所有日志功能测试完成！');
    console.log('✅ 日志记录、统计分析、报告生成功能均正常工作');

  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error);
    process.exit(1);
  } finally {
    // 清理资源
    if (server) {
      // DatabaseMCPServer 没有 stop 方法，但会自动清理
      console.log('\n🔄 测试完成，资源已清理');
    }
  }
}

// 运行测试
if (import.meta.url === `file://${process.argv[1]}`) {
  testLoggingFeatures().catch(console.error);
}